/*
 * GF_C_MODEL_FINANCE_INDICATOR_UTF8/GF_C_MODEL_FINANCE_INDICATOR_UTF8.c
 */

#include<stdio.h>
#include<string.h> /* memset(); */
#include<malloc.h>
#include<math.h> /* NAN */

#define _DATA_START_INDEX    1
#define _POINTER_START_INDEX 0
#define _DATA_INDEX_DISTANCE _POINTER_START_INDEX - _DATA_START_INDEX

double* _ARRAY_FOR_CLOSE_OF_MAP_SMA;

double MAP_SMA(int INDEX, int PERIOD, double CLOSE) {
    
    if (INDEX == _DATA_START_INDEX) {
        _ARRAY_FOR_CLOSE_OF_MAP_SMA = (double*)realloc(_ARRAY_FOR_CLOSE_OF_MAP_SMA, sizeof(double) * INDEX);
        _ARRAY_FOR_CLOSE_OF_MAP_SMA[(INDEX + _DATA_INDEX_DISTANCE)] = CLOSE;
        /* .......................................... */
        return NAN;
    } else if (INDEX < PERIOD) {
        _ARRAY_FOR_CLOSE_OF_MAP_SMA = (double*)realloc(_ARRAY_FOR_CLOSE_OF_MAP_SMA, sizeof(double) * INDEX);
        _ARRAY_FOR_CLOSE_OF_MAP_SMA[(INDEX + _DATA_INDEX_DISTANCE)] = CLOSE;
        /* .......................................... */
        return NAN;
    } else {
        _ARRAY_FOR_CLOSE_OF_MAP_SMA = (double*)realloc(_ARRAY_FOR_CLOSE_OF_MAP_SMA, sizeof(double) * INDEX);
        _ARRAY_FOR_CLOSE_OF_MAP_SMA[(INDEX + _DATA_INDEX_DISTANCE)] = CLOSE;
        /* .......................................... */
        int MOVING = INDEX + _DATA_INDEX_DISTANCE;
        int ENDING = MOVING - PERIOD + 1;
        double TOTAL = 0.0;
        while (MOVING >= ENDING) {
            TOTAL = TOTAL + _ARRAY_FOR_CLOSE_OF_MAP_SMA[MOVING];
            MOVING--;
        }
        double VALUE = TOTAL / PERIOD;
        /* .......................................... */
        return VALUE;
    }
}

